package com.sjy.mvvmdemo.main

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.sjy.mvvmdemo.R
import com.sjy.mvvmdemo.databinding.ItemBinding

/**
 * 没有绑定room的普通RecyclerView
 */
class MainAdapter() : RecyclerView.Adapter<MainAdapter.MyHolder>() {

    var mList = ArrayList<Person>()
    lateinit var clickListener: View.OnClickListener
    fun updateData(items: ArrayList<Person>) {
        this.mList = items
        notifyDataSetChanged()
    }

    //编写顺序(1)
    class MyHolder(private val binding: ItemBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(p: Person, listener: View.OnClickListener) {
            binding.apply {
                clickListener = listener//绑定xml点击事件
                mPerson = p//绑定xml数据
                executePendingBindings()//强制更新
            }
        }
    }

    //编写顺序(2)
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        //item.xml的binding是ItemBinding
        val binding =
            DataBindingUtil.inflate<ItemBinding>(layoutInflater, R.layout.item, parent, false)
        return MyHolder(binding)
    }

    //编写顺序(3)
    override fun getItemCount(): Int {
        return mList!!.size
    }

    //编写顺序(4)
    override fun onBindViewHolder(holder: MyHolder, position: Int) {

        var mPerson = mList!![position] ?: return
        //绑定数据
        holder.apply {
            bind(mPerson, clickListener)
        }
    }
}


